<template>
  <section>
    <!--#region 搜索条-->

    <xt-search @search="handleSearch">
      <el-input v-model="filters.code" :placeholder="$t('custom.code')" size="small" class="search-box__input" style="width:230px"
                clearable @keyup.enter.native="handleSearch"></el-input>
      <el-input v-model="filters.name" :placeholder="$t('custom.name')" size="small" class="search-box__input" style="width:230px"
                clearable @keyup.enter.native="handleSearch"></el-input>
      <el-input v-model="filters.phone" :placeholder="$t('custom.phone')" size="small" class="search-box__input" style="width:230px"
                clearable @keyup.enter.native="handleSearch"></el-input>
      <el-input v-model="filters.address" :placeholder="$t('custom.address')" size="small" class="search-box__input" style="width:230px"
                clearable @keyup.enter.native="handleSearch"></el-input>
      <el-input v-model="filters.fax" :placeholder="$t('custom.fax')" size="small" class="search-box__input" style="width:230px"
                clearable @keyup.enter.native="handleSearch"></el-input>
      <template slot="actions">
        <el-button size="small" class="search-box__button" type="primary" icon="plus" @click="handleAdd"
                   v-if="getOperation('insert')">{{$t('add')}}
        </el-button>
      </template>
    </xt-search>

    <!--#endregion-->

    <!--#region 页面主要列表-->

    <!--列表-->

    <el-table :data="customList" highlight-current-row v-loading="loading.listLoading" style="width: 100%;" stripe
              border>
      <el-table-column align="left" header-align="center" type="index" width="56" :label="$t('index')">
        <template slot-scope="scope">
          {{(pageInfo.pageIndex-1)*pageInfo.pageSize+scope.$index+1}}
        </template>
      </el-table-column>
      <el-table-column align="left" header-align="center" prop="code" :label="$t('custom.code')" min-width="100"
                       :show-overflow-tooltip="true"></el-table-column>
      <!--<el-table-column align="left" header-align="center" prop="shortName" :label="$t('custom.shortName')" min-width="100"
                       :show-overflow-tooltip="true"></el-table-column>-->
      <el-table-column align="left" header-align="center" prop="name" :label="$t('custom.name')" min-width="250"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column align="left" header-align="center" prop="areaName" :label="$t('custom.areaName')" min-width="100"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column align="left" header-align="center" prop="salesManName" :label="$t('custom.salesManName')" min-width="100"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column align="left" header-align="center" prop="operatorName" :label="$t('custom.operatorName')" min-width="100"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column align="left" header-align="center" prop="director" :label="$t('custom.director')" min-width="100"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column align="left" header-align="center" prop="tel" :label="$t('custom.tel')" min-width="100"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column align="left" header-align="center" prop="phone" :label="$t('custom.phone')" min-width="100"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column align="left" header-align="center" prop="address" :label="$t('custom.address')" min-width="100"
                       :show-overflow-tooltip="true"></el-table-column>
      <!--<el-table-column align="left" header-align="center" prop="taxId" :label="$t('custom.taxId')" min-width="100"
                       :show-overflow-tooltip="true"></el-table-column>-->
      <!--<el-table-column align="left" header-align="center" prop="mail" :label="$t('custom.mail')" min-width="100"
                       :show-overflow-tooltip="true"></el-table-column-->>
      <!--<el-table-column align="left" header-align="center" prop="site" :label="$t('custom.site')" min-width="100"
                       :show-overflow-tooltip="true"></el-table-column>-->
      <el-table-column align="left" header-align="center" prop="fax" :label="$t('custom.fax')" min-width="100"
                       :show-overflow-tooltip="true"></el-table-column>
      <!--<el-table-column prop="areaId" align="center" :label="$t('custom.areaId')" min-width="100" :show-overflow-tooltip="true"> </el-table-column>-->
      <!--<el-table-column prop="areaCode" align="center" :label="$t('custom.areaCode')" min-width="100" :show-overflow-tooltip="true"></el-table-column>-->


      <!--<el-table-column prop="yearBalance" align="center" :label="$t('custom.yearBalance')" min-width="100"
                       :show-overflow-tooltip="true"></el-table-column>-->
      <!--<el-table-column align="left" header-align="center" prop="payDay" :label="$t('custom.payDay')" min-width="80"
                       :show-overflow-tooltip="true"></el-table-column>-->
      <el-table-column align="left" header-align="center" prop="payMode" :label="$t('custom.payDay')" min-width="80"
                       :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{getPayModeByKey(scope.row.payMode)}}
        </template>
      </el-table-column>
      <!--<el-table-column align="left" header-align="center" prop="post" label="邮编" min-width="100"
                       :show-overflow-tooltip="true"></el-table-column>-->
      <!--<el-table-column align="left" header-align="center" prop="remark" label="备注" min-width="100"
                       :show-overflow-tooltip="true"></el-table-column>-->
      <el-table-column align="left" header-align="center" :label="$t('operation')" width="150" v-if="getOperation('update|delete')">
        <template slot-scope="scope">
          <el-button size="mini" type="warning" @click="handleEdit(scope.row,scope.$index)"
                     v-if="getOperation('update')">{{$t('modify')}}
          </el-button>
          <el-button type="danger" size="mini" @click="deleteData(scope.row,scope.$index)"
                     v-if="getOperation('delete')">{{$t('delete')}}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!--#endregion-->

    <!--#region 工具条-->

    <!--工具条-->

    <el-row>
      <el-col :span="24" class="toolbar">
        <el-pagination
          style="float:right;"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageInfo.pageIndex"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="pageInfo.pageSize"
          layout="sizes, prev, pager, next"
          :total="pageInfo.count">
        </el-pagination>
      </el-col>
    </el-row>

    <!--#endregion-->

    <!--#region 新增修改页面-->

    <!--新增界面-->

    <!--新增界面-->
    <el-dialog width="95%" top="20px" :title="formData.id==0?$t('add'):$t('modify')" :visible.sync="dialog.formDataVisible"
               :close-on-click-modal="false" :modal-append-to-body="false">
      <el-form class="main-table" :model="formData" label-width="100px" :rules="formRules" ref="formData">
        <!--<el-form-item :label="$t('custom.code')" prop="code">
          <el-input v-model="formData.code" auto-complete="off" :maxlength="50" :placeholder="$t('custom.validateCode')"
                    size="small"></el-input>
        </el-form-item>-->
        <el-form-item :label="$t('custom.name')" prop="name">
          <el-input v-model="formData.name" auto-complete="off" :maxlength="50" :placeholder="$t('custom.validateName')"
                    size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('custom.shortName')" prop="shortName">
          <el-input v-model="formData.shortName" auto-complete="off" :maxlength="20" :placeholder="$t('custom.validateShortName')"
                    size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('custom.areaId')" prop="areaId">
          <vue-tree-select
            v-model="formData.areaId"
            :options="areaList"
            :multiple="false"
            :placeholder="$t('custom.validateAreaId')"
            :noChildrenText="$t('noData')"
            :noOptionsText="$t('noData')"
            size="small">
          </vue-tree-select>
          <!--<el-select v-model="formData.areaId" :placeholder="$t('custom.validateAreaId')" size="small" @change="changeArea">
            <el-option v-for="(item,index) in areaList" :key="index" :label="item.name" :value="item.id"></el-option>
          </el-select>-->
        </el-form-item>
        <el-form-item :label="$t('custom.salesManId')" prop="salesManId">
          <el-select v-model="formData.salesManId" :placeholder="$t('custom.validateSalesManId')" size="small" @change="changeSalesMan">
            <el-option v-for="(item,index) in salesManList" :key="index" :label="item.name"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('custom.operatorId')" prop="operatorId">
          <el-select v-model="formData.operatorId" :placeholder="$t('custom.validateOperatorId')" size="small" @change="changeOperator">
            <el-option v-for="(item,index) in operatorList" :key="index" :label="item.name"
                       :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('custom.payMode')" prop="payMode">
          <el-select v-model="formData.payMode" :placeholder="$t('custom.validatePayMode')" size="small">
            <el-option v-for="(item,index) in payModeList" :key="index" :label="item.value"
                       :value="item.key"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('custom.director')" prop="director">
          <el-input v-model="formData.director" auto-complete="off" :maxlength="20" :placeholder="$t('custom.validateDirector')"
                    size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('custom.tel')" prop="tel">
          <el-input v-model="formData.tel" auto-complete="off" :maxlength="20" :placeholder="$t('custom.validateTel')"
                    size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('custom.phone')" prop="phone">
          <el-input v-model="formData.phone" auto-complete="off" :maxlength="20" :placeholder="$t('custom.validatePhone')"
                    size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('custom.address')" prop="address">
          <el-input v-model="formData.address" auto-complete="off" :maxlength="50" :placeholder="$t('custom.validateAddress')"
                    size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('custom.mail')" prop="mail">
          <el-input v-model="formData.mail" auto-complete="off" :maxlength="50" :placeholder="$t('custom.validateMail')"
                    size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('custom.site')" prop="site">
          <el-input v-model="formData.site" auto-complete="off" :maxlength="50" :placeholder="$t('custom.validateSite')"
                    size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('custom.fax')" prop="fax">
          <el-input v-model="formData.fax" auto-complete="off" :maxlength="20" :placeholder="$t('custom.validateFax')"
                    size="small"></el-input>
        </el-form-item>
        <!--<el-form-item :label="$t('custom.yearBalance')" prop="yearBalance">
          <el-input type="number" v-model.number="formData.yearBalance" auto-complete="off" :maxlength="20"
                    :placeholder="$t('custom.validateYearBalance')" size="small"></el-input>
        </el-form-item>-->
        <!--<el-form-item :label="$t('custom.payDay')" prop="payDay">
          <el-input v-model.number="formData.payDay" :min="1" auto-complete="off" :maxlength="9"
                    :placeholder="$t('custom.validatePayDay')" size="small" :controls="false"
                    style="width:100%"></el-input>
        </el-form-item>-->
        <el-form-item :label="$t('custom.post')" prop="post">
          <el-input v-model="formData.post" auto-complete="off" :maxlength="6" :placeholder="$t('custom.validatePost')"
                    size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('custom.taxId')" prop="taxId">
          <el-input v-model="formData.taxId" auto-complete="off" :maxlength="20" :placeholder="$t('custom.validateTaxId')"
                    size="small"></el-input>
        </el-form-item>
        <el-form-item :label="$t('custom.remark')" prop="remark" style="width: 97%">
          <el-input v-model="formData.remark" auto-complete="off" :maxlength="255" :placeholder="$t('custom.validateRemark')" size="small"
                    type="textarea" resize="none"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="handleCancel">{{$t('cancel')}}</el-button>
        <el-button type="primary" @click.native="submitData" :loading="loading.addLoading">{{$t('submit')}}</el-button>
      </div>
    </el-dialog>

    <!--#endregion-->

  </section>
</template>

<script>

  /*#region 导入函数*/

  import PagePlugIn from "../../../mixins/page-plug-in";
  import {AreaAPI, CustomAPI, DictAPI, UserAPI} from "../../../modules";
  import VueTreeSelect from "../../../components/vue-tree-select-validate/vue-tree-select-validate.vue";
  import {ParamsSelect} from "../../../utils/utils";
  import {SystemParameterEnum} from "../../../modules/enums";

  /*#endregion*/

  export default {
    name: "Custom",
    methods: {

      /*#region 自定义函数(组件change事件等)*/

      getPayModeByKey(payMode) {
        const find = this.payModeList.find((d) => d.key === payMode);
        return find ? find.value : "";
      },
      changeOperator() {
        const find = this.operatorList.find((d) => d.id === this.formData.operatorId);
        this.formData.operatorName = find ? find.name : "";
      },
      changeSalesMan() {
        const find = this.salesManList.find((d) => d.id === this.formData.salesManId);
        this.formData.salesManName = find ? find.name : "";
      },

      /*#endregion*/

      /*#region 数据提交事件*/

      //提交事件

      submitData() {
        this.$refs.formData.validate((valid) => {
          if (valid) {
            if (this.formData.areaId) {
              ParamsSelect.getAddSelectParams(this.formData, this.areaList, {
                areaName: "name",
                areaCode: "code"
              }, {areaId: "id"});
            }
            const params = JSON.parse(JSON.stringify(this.formData));
            if (params.id === 0) {
              this.loading.addLoading = true;
              CustomAPI.insertCustom(params).then(({data}) => {
                if (data.code === 1) {
                  this.$refs.formData.resetFields();
                  this.getMainList();
                  this.dialog.formDataVisible = false;
                }
                this.loading.addLoading = false;
              });
            } else {
              this.loading.addLoading = true;
              CustomAPI.updateCustom(params).then(({data}) => {
                if (data.code === 1) {
                  this.$refs.formData.resetFields();
                  this.getMainList();
                  this.dialog.formDataVisible = false;
                }
                this.loading.addLoading = false;
              });
            }
          }
        });
      },

      //删除

      deleteData(row) {
        this.$confirm(this.$t('deleteConfirm'), this.$t('tips'), {
          confirmButtonText: this.$t('confirm'),
          cancelButtonText: this.$t('cancel'),
          type: "warning"
        }).then(() => {
          CustomAPI.deleteCustom({id: row.id}).then(({data}) => {
            if (data.code === 1) {
              this.getMainList();
            }
          });
        });
      },


      /*#endregion*/

      /*#region 操作函数(handle)*/

      //修改

      handleEdit(row) {
        this.$refs.formData && this.$refs.formData.resetFields();
        this.formData = JSON.parse(JSON.stringify(row));
        this.dialog.formDataVisible = true;
      },
      handleCancel() {
        this.dialog.formDataVisible = false;
      },
      handleAdd() {
        this.$refs.formData && this.$refs.formData.resetFields();
        this.formData = CustomAPI.init();
        this.dialog.formDataVisible = true;
      },

      /*#endregion*/

      /*#region 获取数据*/

      //付款方式
      getPayModeList() {
        DictAPI.listDict({type: SystemParameterEnum.PayModeType.type, pageSize: 999}).then(({data, list}) => {
          this.payModeList = list || [];
          this.getMainList();
        });
      },
      getMainList() {
        const params = {
          ...this.getParams(),
          orderBy: "Id desc"
        };
        CustomAPI.listCustom(params).then(({data, list}) => {
          this.customList = list;
          this.pageInfo.pageIndex = data.data ? data.data.currentPage : 1;
          this.pageInfo.count = data.data ? data.data.count : 0;
        });
      }

      /*#endregion*/

    },

    /*#region 生命周期函数(created、mount、等)*/

    created() {
      this.getPayModeList();
      const _this = this;
      //业务员
      DictAPI.listDict({...SystemParameterEnum.OperatorRoleIds, pageSize: 1}).then(({res, list}) => {
        const roleIds = list && list.length > 0 ? list[0].value : "";
        UserAPI.listUserByRoleId({roleId: roleIds}).then(({res, list}) => {
          _this.operatorList = list ? list : [];
        });
      });

      //后勤人员
      DictAPI.listDict({
        ...SystemParameterEnum.SalesManRoleIds, pageSize: 1
      }).then(({res, list}) => {
        const roleIds = list && list.length > 0 ? list[0].value : "";
        UserAPI.listUserByRoleId({roleId: roleIds}).then(({res, list}) => {
          _this.salesManList = list ? list : [];
        });
      });

      //地区
      AreaAPI.listAreaTree().then(({res, list}) => {
        _this.areaList = list ? list : [];
      });
    },

    /*#endregion*/

    /*#region 注册绑定数据*/
    components: {
      VueTreeSelect
    },
    mixins: [PagePlugIn],
    data() {
      const checkPayDay = (rule, value, callback) => {
        const reg = /^\d+$/;
        if (value && !reg.test(value)) {
          callback(new Error(this.$t('custom.validateIntNumber')));
        } else {
          callback();
        }
      };
      return {
        filters: CustomAPI.init(),
        formData: CustomAPI.init(),
        formRules: {

          /*code: [{required: true, message: '此项不能为空'}],*/
          name: [{required: true, message: this.$t('custom.validateName')}],
          salesManId: [{required: true, message: this.$t('custom.validateSalesManId'), type: "number", trigger: "change"}],
          operatorId: [{required: true, message: this.$t('custom.validateOperatorId'), type: "number", trigger: "change"}],
          areaId: [{required: true, message: this.$t('custom.validateAreaId'), trigger: "change", type: "number"}],
          post: [{pattern: /^[1-9]\d{5}$/, message: this.$t('custom.validateFormatPost')}],
          mail: [{type: "email", message: this.$t('custom.validateFormatMail')}]
          // payDay: [{pattern: /^\d+$/, message: "请输入正整数"}]
        },
        dialog: {formDataVisible: false},
        loading: {addLoading: false, listLoading: false},
        customList: [],
        operatorList: [],
        salesManList: [],
        areaList: [],
        payModeList: []
      };
    }

    /*#endregion */

  };
</script>

<style scoped lang="scss">
  .main-table {
    .el-form-item {
      width: 32%;
      display: inline-block;
    }
  }
</style>
